package se.spot4j.model;



import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;




public class Client {
   private static final String BASEURL = "http://ws.spotify.com";
   private static final String SEARCH = "/search";
   private static final String LOOKUP = "/lookup";
   private static final String VERSION = "/1";
   private static final String ALBUM = "/album?q=";
   private static final String ARTIST = "/artist?q=";
   private static final String TRACK = "/track?q=";

   public static void main(String[] args) {
              try {
           HttpClient httpclient = new DefaultHttpClient();
           HttpGet httpget = new HttpGet(BASEURL + SEARCH + VERSION + ARTIST + "madonna");
           HttpResponse response = httpclient.execute(httpget);
           HttpEntity entity = response.getEntity();
           if (entity != null) {
               entity = new BufferedHttpEntity(entity);
               SAXBuilder saxbuilder = new SAXBuilder();
               Document doc = saxbuilder.build(new StringReader(EntityUtils.toString(entity)));
               XPath artistPath = XPath.newInstance("//ns:artist");
               artistPath.addNamespace("ns", "http://www.spotify.com/ns/music/1");
               List artists = artistPath.selectNodes(doc);
               Iterator i = artists.iterator();
               System.out.println(artists.size());
               while (i.hasNext()) {
                   Element artist = (Element)i.next();
                   Element e = artist.getChild("name", artist.getNamespace());
                   System.out.println(e.getValue());

               }
              //
              System.out.println(EntityUtils.toString(entity));
           } else {
               System.out.println("nothing returned");
           }


       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } catch (JDOMException e) {
           e.printStackTrace();
              } finally {

       }
   }
   }


